class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& prerequisites)
    {
        vector<vector<int>> edge(n);
        vector<int> in(n);
        for (auto e : prerequisites)
        {
            int a = e[0], b = e[1];
            //b --> a
            edge[b].push_back(a);
            in[a]++;
        }
        queue<int> q;
        for (int i = 0; i < n; i++)
        {
            if (in[i] == 0) q.push(i);
        }
        while (q.size())
        {
            int front = q.front();
            q.pop();
            for (auto e : edge[front])
            {
                in[e]--;
                if (in[e] == 0) q.push(e);
            }
        }
        for (int i = 0; i < n; i++)
        {
            if (in[i] != 0) return false;
        }
        return true;
    }
};
class Solution {
public:
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites)
    {
        unordered_map<int, vector<int>> hash(n);
        vector<int> in(n);
        for (auto e : prerequisites)
        {
            int a = e[0];
            int b = e[1];
            // b -> a
            hash[b].push_back(a);
            in[a]++;
        }
        queue<int> q;
        for (int i = 0; i < n; i++)
        {
            if (in[i] == 0) q.push(i);
        }
        vector<int> ret;
        while (q.size())
        {
            int front = q.front();
            q.pop();
            ret.push_back(front);
            for (auto e : hash[front])
            {
                in[e]--;
                if (in[e] == 0) q.push(e);
            }
        }

        for (int i = 0; i < n; i++)
        {
            if (in[i] != 0) return {};
        }
        return ret;
    }
};